package com.atguigu.day1;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 可重入锁又名递归锁，是指在同一个线程中，外层获取锁的时候，再进入该线程的内层方法会自动获取锁。
 * Java中ReentrantLock和synchronized都是可重入锁，可重入锁的一个优点是‘可一定程度避免死锁‘
 */
public class ReentrantLockDemo {
    public synchronized void a1(){
        this.b2();
        System.out.println("a");
    }

    public synchronized void b2(){
        System.out.println("b");
    }


    public static void main(String[] args) {
        ReentrantLockDemo reentrantLockDemo = new ReentrantLockDemo();
        reentrantLockDemo.c3();
    }

    private Lock lock = new ReentrantLock(true);
    public void c3(){
        lock.lock();
        try {
            d4();
            System.out.println("c");
        }finally {
            lock.unlock();
        }
    }
    public void d4(){
        lock.lock();
        try {
            System.out.println("d");
        }finally {
            lock.unlock();
        }
    }
}
